<template>
  <div class="editForm-wrapper">
    <!-- 客户编辑dialog-->
    <el-dialog
        :title="title"
        :close-on-click-modal="false"
        v-dialogDrag
        :visible.sync="editVisible"
    >
      <el-form
          label-width="165px"
          :rules="dataRule"
          ref="editForm"
          :model="editForm"
      >
        <el-form-item label="客户类型:" prop="types">
          <el-radio-group :disabled="method === 'edit'" v-model="editForm.types" @change="changeHandlerType">
            <el-radio
                v-for="item in $dictUtils.getDictList('companyType')"
                :key="item.value"
                :label="Number(item.value)"
            >{{ item.label }}
            </el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户名称:" prop="fullNames"
                      :rules=" [{ required: true, message: '请输入客户名称', trigger: 'blur' },{validator:replaceFullName, trigger:'blur'}]">
          <!--<el-input maxlength="30" show-word-limit v-model.trim="editForm.fullNames"></el-input>-->
          <el-autocomplete 
            	placeholder="请输入客户名称"
            	:debounce="0"
            	:fetch-suggestions="remoteMethod"
            	:trigger-on-focus="true"
            	v-model.trim="editForm.fullNames"
            	@select="handleSelect"
            	@change="handleChange"
            	:maxlength="30" show-word-limit
            	clearable>
	            <template slot-scope="{ item }">
	              <section class="querySearch-autocomplete">
	                <section class="name-item">
	                  <section class="name"><span v-if="item.value">{{ item.value.substr(0, 1) }}</span>
	                  </section>
	                  {{ item.value|ellipsis(15) }}
	                </section>
	                <section>
	                </section>
	              </section>
	            </template>
	          </el-autocomplete>
        </el-form-item>
        <el-form-item label="客户简称:">
          <el-autocomplete
              :debounce="0"
              :fetch-suggestions="querySearch" @select="toHandleSelect($event,'1')"
              :trigger-on-focus="false" v-model="editForm.names">
            <template slot-scope="{ item }">

              <section class="querySearch-autocomplete">
                <section class="name-item">
                  <section class="name"><span v-if="item.contactName">{{ item.contactName.substr(0, 1) }}</span>
                  </section>
                  {{ item.contactName }}
                  ({{ item.contactPhone }})
                </section>
                <section>
                </section>
              </section>

              <div></div>
              <!-- <span class="addr">{{ item.address }}</span> -->
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item prop="codes" label="统一社会信用代码:"
                      v-if="editForm.types!==Number($dictUtils.getDictList('companyType')[0].value)" disabled
                      :rules=" [
          { required: editForm.types !== Number($dictUtils.getDictList('companyType')[0].value), message: '社会信用统一代码不能为空', trigger: 'blur' },
          {validator:checkRepeatCode, trigger:'blur'}
        ]">

          <el-input maxlength="18" show-word-limit v-model.trim="editForm.codes"
                    :disabled="method==='edit'&&editForm.codes!=''"></el-input>
        </el-form-item>
        <el-form-item label="身份证号:" prop="idCard" :rules=" [
          { required: editForm.types === Number($dictUtils.getDictList('companyType')[0].value), message: '身份证不能为空', trigger: 'blur' },
          {validator:checkRepeatIdCard, trigger:'blur'}
        ]">
          <el-input maxlength="18" show-word-limit v-model.trim="editForm.idCard"
                    :disabled="method==='edit'"></el-input>
        </el-form-item>
        <el-form-item label="联系人姓名:">
          <el-input maxlength="10" show-word-limit v-model.trim="editForm.contactName"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话:" prop="contactPhone"
                      :rules=" [ {validator:checkPhoneNumber, trigger:'blur'}]">
          <el-input maxlength="11" show-word-limit v-model="editForm.contactPhone"></el-input>
        </el-form-item>
        <!--<el-form-item label="所在地区:" prop="countyCode">

        </el-form-item>-->
        <el-form-item label="所在地区:" prop="countyCode">
          <section style="width:320px">
            <Area class="areaselect-adjust" ref="area" @getArea="getArea1"></Area>
          </section>
        </el-form-item>
        <el-form-item label="详细地址:" prop="detailAddress">
          <div class="add_textArea" >
            <el-input type="textarea" v-model="editForm.detailAddress" v-filter-special-char="editForm.detailAddress"
                      :rows="2" placeholder="请选择地址"
                      maxlength="50" show-word-limit >
            </el-input>
            <div class="addIcon" @click="openMap"><i></i></div>

            <!--          <el-input type="textarea" v-model="editForm.detailAddress"-->
            <!--                     readonly-->
            <!--                    placeholder="请输入详细地址" class="adjustWordLimit" maxlength="50" show-word-limit>-->
            <!--          </el-input>-->
            <!--          <i @click="openMap"></i>-->
          </div>
          <!--                  <el-input  v-model="form.detailAddress"  :rows="2" v-filter-special-char="" placeholder="请选择地址"-->
          <!--                            maxlength="50"   show-word-limit  readonly >-->
          <!--                  </el-input>-->
          <!--                  <div class="readOnly" @click="openMap"></div>-->
          <!--                  <div class="addIcon" @click="openMap"><i></i></div>-->


          <!--                    <el-input type="textarea" maxlength="50" show-word-limit v-model.trim="editForm.detailAddress"></el-input>-->
          <!--                    <el-link icon="el-icon-search" @click="openMap" type="danger" :underline="false" >地图标点</el-link>-->
        </el-form-item>
        <!--                <div class="content-more">-->
        <!--                    <el-form-item label="经度纬度:" prop="lng" :rules="[-->
        <!--                  {validator: validator.checkLon, trigger:'blur'}-->
        <!--                 ]">-->
        <!--                        <el-input maxlength="20" show-word-limit v-model.trim="editForm.lng" placeholder="请输入经度"></el-input>-->
        <!--                    </el-form-item>-->
        <!--                    <el-form-item prop="lat" :rules="[-->
        <!--                  {validator: validator.checkLat, trigger:'blur'}-->
        <!--                 ]">-->
        <!--                        <el-input  maxlength="20" show-word-limit v-model.trim="editForm.lat" placeholder="请输入纬度"></el-input>-->
        <!--                        <span>-->
        <!--&lt;!&ndash;                        <el-link icon="el-icon-search" @click="openBMap" type="danger" :underline="false">地图标点</el-link>&ndash;&gt;-->
        <!--                    </span>-->
        <!--                    </el-form-item>-->
        <!--                </div>-->

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="doSubmit()" v-noMoreClick
        >确定</el-button
        >
        <el-button size="small" @click="close()">取消</el-button>
      </span>
    </el-dialog>
    <div>
      <el-dialog
          :title="title"
          :close-on-click-modal="false"
          v-dialogDrag
          :visible.sync="detailsVisible"
          class="tableDialog tableFormDialog"
      >
        <div class="detail">
          <table class="detail-table" cellspacing="0" cellpadding="0">

            <tr class="view-container">
              <td class="label-container">类型</td>
              <td class="form-container">
                <span v-if="viewForm.types === 1">企业</span>
                <span v-if="viewForm.types===2">个人</span>
              </td>
              <td class="label-container">客户名称</td>
              <td class="form-container">{{ viewForm.fullNames }}</td>
            </tr>
            <tr class="view-container">
              <td class="label-container">客户简称</td>
              <td class="form-container">{{ viewForm.names }}</td>
              <td class="label-container">统一社会信用代码</td>
              <td class="form-container">{{ viewForm.codes }}</td>

            </tr>
            <tr class="view-container">
              <td class="label-container">身份证号</td>
              <td class="form-container">{{ viewForm.idCard }}</td>
              <td class="label-container">联系人姓名</td>
              <td class="form-container">{{ viewForm.contactName }}</td>
            </tr>
            <tr class="view-container">
              <td class="label-container">联系人电话</td>
              <td class="form-container">{{ viewForm.contactPhone }}</td>
              <td class="label-container">所在地区</td>
              <td class="form-container" colspan="3">
                {{ viewForm.countyCode }}
              </td>
            </tr>
            <tr class="view-container">
              <td class="label-container">详细地址</td>
              <td class="form-container" colspan="3">{{ viewForm.detailAddress }}</td>
            </tr>
            <tr class="view-container map">
              <td class="label-container">经度纬度</td>
              <td class="form-container" colspan="3"><span>{{ viewForm.lng }}</span><span>{{ viewForm.lat }}</span></td>
            </tr>
          </table>
        </div>
      </el-dialog>
    </div>
      <g-map ref="gmap" :showCity="true" @saveDetailAddress="saveDetailAddress"></g-map>
    <CompanyDialog ref="CompanyDialog" @getCompanyData="getCompanyData"></CompanyDialog>
  </div>
</template>
<script>
import {edit, checkRepeat, getSearchlist,companySearch} from '@/api/market/crm.js'
import {getAreaByCode} from '@/api/area.js'
import Area from '@/components/area/area'
import CompanyDialog from '@/components/dialog/queryAllCompanyDialog.vue'
import gMap from '@/components/gMap/gmap'
// import BMap from '@/components/BMap/BMap'
// import BMap from '@/components/BMap/BMap'

export default {
  components: {
    Area,
    gMap,
    CompanyDialog
  },
  data() {
    return {
      areaLabel: {},
      method: '',
      mapVisible: false,
      title: '',
      editForm: {
        types: 1,
        names: '',
        fullNames: '',
        codes: '',
        lng: "",
        lat: "",
        idCard: '',
        contactName: '',
        contactPhone: '',
        countyCode: '',
        detailAddress: '',
        id: '',
        addressId: ''
      },
      viewForm: {
        types: '',
        names: '',
        codes: '',
        lng: "",
        lat: "",
        idCard: '',
        contactName: '',
        contactPhone: '',
        countyCode: '',
        detailAddress: '',
        id: '',
        addressId: ''
      },
      editVisible: false,
      detailsVisible: false,
      dataRule: {
        names: [{required: true, message: '请输入客户名称', trigger: 'blur'}],
        types: [
          {required: true, message: '请选择客户类型', trigger: 'change'}
        ],
        countyCode: [
          {required: true, message: '请输入公司所在地', trigger: 'change'}
        ],
        contactPhone: [
          {required: true, message: '请输入联系人电话', trigger: 'blur'}
        ],
        contactName: [
          {required: true, message: '请输入联系人姓名', trigger: 'blur'}
        ],
        detailAddress: [
          {required: true, message: '请输入详细地址', trigger: ['change','blur']}
        ]
      }
    }
  },
  methods: {
  	// 客户名称联想搜索
	    remoteMethod (keyword, cb) {
	      let params = {
	      	pageNo:1,
	      	pageSize:5,
	        fullNames: keyword
	      }
	      companySearch(params).then((res) => {
	        if (res.data.code === '200') {
	          if (res.data.result) {
	            let data = res.data.result
	            this.values = []
	            data.forEach((item, index) => {
	              let element = {
	                companyId: item.companyId,
	                companySn: item.companySn,
	                value: item.fullName
	              }
	              this.values.push(element)
	            })
	            cb(this.values)
	          } else {
	            cb([])
	          }
	        } else {
	          cb([])
	        }
	      })
	      // 调用 callback 返回建议列表的数据
	    },
	    handleChange (val) {
	    	console.log(299,val)
	    },
	    // 选择所属企业信息
	    handleSelect (item) {
	    	console.log(307,item)
//	  		this.$set(this.editForm,"companyId",item.companyId)
//	  		this.$set(this.editForm,"companySn",item.companySn)
	    },
    //  打开地图
    openMap() {
      this.$refs.gmap.mapVisible = true
      this.$nextTick(() => {
        this.$refs.gmap.initMap(this.cityCode)
      })
    },
    // 保存地图子页面传来的数据，完成详细地址字段
    saveDetailAddress(str) {
      let item = JSON.parse(str)
      let i = item.addressComponent.split(';')
      this.editForm.lat = item.location.lat
      this.editForm.lng = item.location.lng
      if (i.length == 3) {
        this.editForm.province = i[0]
        this.editForm.city = i[1]
        this.editForm.district = i[2]
      } else {
        //处理北京市、天津市、上海市这些
        this.editForm.province = i[0]
        this.editForm.city = i[0]
        this.editForm.district = i[1]
      }
      this.editForm.detailAddress = item.address

    },
    handleClose(done) {
      this.$Msg.confirm({
        title: '您确定要关闭吗？',
        content: this.GLOBAL.FORM_CLOSE_TIPS,
        confirmCall: () => {
          done();
        }
      })
    },
    //输入完选择
    toHandleSelect($event, item) {
      console.log(362,$event)
      this.editForm.codes = $event.codes;
      this.editForm.idCard = $event.idCard;
      this.editForm.contactName = $event.contactName
      this.editForm.contactPhone = $event.contactPhone;
      if (
          $event.countyCode !== '' &&
          typeof $event.countyCode !== 'undefined'
      ) {
        let area = JSON.parse($event.countyCode)
        let that = this
        this.$nextTick(() => {
          that.$refs.area.province = area.province
          that.$refs.area.city = area.city
          that.$refs.area.district = area.district
        })
      }
    },
    querySearch(queryString, cb) {
      if (queryString) {
        getSearchlist({
          selectValue: queryString,
          state: 1
        }).then((res) => {
          console.log(385,res)
          if (res.data.code === '200') {

            this.values = []
            for (let index = 0; index < res.data.result.length; index++) {
              let element = {
                id: '',
                value: '',
                contactPhone: '',
                idCard: '',
                codes: '',
                contactName: '',
                countyCode: ''
              }
              element.id = res.data.result[index].id
              element.contactName = res.data.result[index].contactName
              element.codes = res.data.result[index].codes
              element.value = res.data.result[index].names
              element.contactPhone = res.data.result[index].contactPhone
              element.idCard = res.data.result[index].idCard
              element.countyCode = res.data.result[index].countyCode
              this.values.push(element);
            }
            cb(this.values)
          }
        })
      }
      // 调用 callback 返回建议列表的数据
    },
    // 打开地图弹窗
    openBMap() {
      this.mapVisible = true;
    },
    // 经纬度数据回显
    getlngAndlat(val) {
      this.mapVisible = false;
      this.editForm.lat = val.lat.toString();
      this.editForm.lng = val.lng.toString();
    },
    // 往来选择弹窗
    getCompanyClientByName() {
      if (this.editForm.names) {
        this.$nextTick(() => {
          this.$refs['CompanyDialog'].getCompanyList(this.$refs['CompanyDialog'].page, this.editForm.names)
          this.$refs['CompanyDialog'].dialogVisible = true
        })

      }
    },
    // 客户选择数据回显
    getCompanyData(row) {
      this.editForm.names = row.names
      this.editForm.contactName = row.contactName
      this.editForm.contactPhone = row.contactPhone
      this.editForm.idCard = row.idCard
      this.editForm.codes = row.codes
      this.dialogVisible = false
    },
    init(method, editForm) {
      if (method === 'add') {
        this.editVisible = true
        this.method = method
        this.$nextTick(() => {
          this.$refs.editForm.resetFields()
          // this.editForm = {}
          this.editForm.codes = ''
          let that = this
          this.$nextTick(() => {
            that.$refs.area.province = ''
            that.$refs.area.city = ''
            that.$refs.area.district = ''
          })
        })

        this.editForm.id = ''
        this.editForm.addressId = ''
        this.title = '新增客户'
      } else if (method === 'edit') {
        this.editVisible = true
        this.method = method
        console.log(465,editForm.countyCode)

        if (
            editForm.countyCode !== '' &&
            typeof editForm.countyCode !== 'undefined'
        ) {
          let area = JSON.parse(editForm.countyCode)
          let that = this
          this.$nextTick(() => {
            that.$refs.area.province = area.province
            that.$refs.area.city = area.city
            that.$refs.area.district = area.district
          })
        } else {
          let that = this
          this.$nextTick(() => {
            that.$refs.area.province = ''
            that.$refs.area.city = ''
            that.$refs.area.district = ''
          })
        }
        this.$nextTick(() => {
          this.$refs.editForm.resetFields()
          this.editForm = editForm
        })

        this.title = '修改客户'
      } else if (method === 'view') {
        this.method = method
        this.viewForm = editForm
        this.detailsVisible = true
        this.title = '客户详情'
        // let areaLabel = JSON.parse(this.viewForm.countyCode)
        // getAreaByCode(areaLabel).then((res) => {
        //     if (res.data.code === '200') {
        //
        //         this.areaLabel = res.data.result.list[0]
        //         console.log(this.areaLabel)
        //     }
        // })
      }
      console.log(506,this.method)
    },
    getArea1(e) {
      if (e.province !== '' && e.city !== '' && e.district !== '') {
        this.editForm.countyCode = JSON.stringify(e)
      } else {
        this.editForm.countyCode = ''
      }
    },
    close() {
      this.editVisible = false
    },
    doSubmit() {
      this.$refs['editForm'].validate((valid) => {
        console.log(520,valid)
        if (valid) {
          if (
              this.editForm.countyCode !== '' &&
              typeof this.editForm.countyCode !== 'undefined'
          ) {
            console.log(526,this.editForm.countyCode)
            this.$set(this.editForm, 'props', 1)
            edit(this.editForm).then((res) => {
              if (res.data.code === '200') {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.editVisible = false
                this.$emit('refreshDataList')
              }
            })
          }
        }
      })
    },

    // 校验手机号
    checkPhoneNumber(rule, value, callback) {
      if (value && (!(/^[1][34578]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
        callback(new Error('手机号码不符合规范'))
      } else {
        callback()
      }
    },
    // 替换名称
    replaceFullName(rule, value, callback) {
      if (value.indexOf("有限责任公司") != -1) {
        this.editForm.names = value.replace('有限责任公司', '');
      } else if (value.indexOf("有限公司") != -1) {
        this.editForm.names = value.replace('有限公司', '');
      } else if (value.indexOf("责任公司") != -1) {
        this.editForm.names = value.replace('责任公司', '');
      } else if (value.indexOf("公司") != -1) {
        this.editForm.names = value.replace('公司', '');
      }
      callback()
    },
    // 选择客户类型
    changeHandlerType(e) {
      this.editForm.types = e
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
    },
    // 身份证重复
    checkRepeatIdCard(rule, value, callback) {
      if (this.method === 'edit') {
        return callback()
      }
      if (value && (!(/\d{17}[\d|x]|\d{15}/).test(value) || (value.length !== 15 && value.length !== 18))) {
        callback(new Error('身份证号码不符合规范'))
      } else {
        callback()
      }
      if (value) {
        checkRepeat({
          props: '1',
          idCard: value
        }).then(res => {
          if (res.data.code !== '200') {
            callback(new Error('客户身份证有重复'))
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    },
    // 社会统一代码重复
    checkRepeatCode(rule, value, callback) {
      if (this.method === 'edit') {
        return callback()
      }
      if (value) {
        checkRepeat({
          props: '1',
          codes: value
        }).then(res => {
          console.log(606,res.data)
          if (res.data.code !== '200') {
            callback(new Error('客户信用代码有重复'))
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
  },
  mounted() {

  }
}
</script>
<style lang="scss" scoped>
.view-container {
  .label-container {
    width: 150px;
  }
}

.detail .map {
  span:first-child {
    margin-right: 15px;
  }
}

.editForm-wrapper ::v-deep.el-dialog__wrapper .el-dialog .el-dialog__body {
  .add_textArea {
    position: relative;



    //i {
    //  display: inline-block;
    //  height: 18px;
    //  width: 14px;
    //  position: absolute;
    //  bottom: 9px;
    //  right: 6px;
    //  z-index: 3;
    //  align-self: flex-start;
    //  background: url("~@/assets/img/dingwei.png");
    //}
  }
  .addIcon {
    width: 30px;
    z-index: 99;
    background: #FFF;
    line-height: initial;
    display: inline-block;
    padding: 0 5px;
    position: absolute;
    bottom: 28px;
    right: 43px;

    i {
      position:absolute;
      display: inline-block;
      height: 18px;
      width: 14px;
      z-index: 4;
      align-self: flex-start;
      background: url("~@/assets/img/dingwei.png");
    }
  }

  .el-form {
    .el-radio__label {
      font-size: 16px;
    }

  }
}

</style>
